package servlet;

import bean.Advice;
import bean.Message;
import bean.PageBean;
import dao.AdviceDao;
import dao.MessageDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author yl
 */
public class AdviceServlet extends HttpServlet {
    private AdviceDao adviceDao = new AdviceDao();
    private MessageDao messageDao = new MessageDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String t = req.getParameter("t");
        JsonWrapper result = new JsonWrapper();
        if (t != null) {
            // 依据 t
            switch (t) {
                case "requests":
                    List<Object> list;
                    try {
                        list = adviceDao.findUnProcessAdvice(null);
                        if (list.size() != 0) {
                            result.setStatus(200);
                            result.setMsg("success");
                        } else {
                            result.setStatus(200);
                            result.setMsg("no record!");
                        }

                        JSONArray jsonArray = new JSONArray();
                        for (Object single : list) {
                            JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                            jsonArray.add(jsonObject);
                        }
                        result.setDataEntry("total", list.size());
                        result.setDataJsonArray("values", jsonArray);
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                    break;
                case "havemsg":
                    try {
                        int count = adviceDao.findUnProcessAdviceCount();
                        result.setDataEntry("total", count);
                        if (count != 0) {
                            result.setStatus(200);
                            result.setMsg("success");
                        } else {
                            result.setStatus(200);
                            result.setMsg("No record!");
                        }
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                    break;
                default:
            }
        } else {
            // 依据 type
            String type = req.getParameter("type");
            if (type != null) {
                String prefix = req.getParameter("prefix");
                String value = req.getParameter("value");
                // 模糊查询
                if (prefix != null) {
                    Advice advice = new Advice();
                    if ("id".equals(type)) {
                        advice.setAdviseId(prefix);
                    } else if ("adminId".equals(type)) {
                        advice.setAdminId(prefix);
                    } else if ("creator".equals(type)) {
                        advice.setCreator(prefix);
                    } else if ("title".equals(type)) {
                        advice.setTitle(prefix);
                    } else if ("content".equals(type)) {
                        advice.setContent(prefix);
                    } else if ("createTime".equals(type)) {
                        advice.setCreateTime(prefix);
                    } else if ("status".equals(type)) {
                        advice.setStatus(prefix);
                    } else if ("replyContent".equals(type)) {
                        advice.setReplyContent(prefix);
                    } else if ("replyTime".equals(type)) {
                        advice.setReplyTime(prefix);
                    }
                    List<Object> resultAdvice;  //查询返回的用户信息
                    try {
                        resultAdvice = adviceDao.adviceList(null, advice, null, null, null, null);
                        if (resultAdvice.size() != 0) {
                            result.setMsg("success");
                        } else {
                            result.setMsg("no record!");
                        }
                        result.setStatus(200);
                        JSONArray jsonArray = new JSONArray();

                        for (Object single : resultAdvice) {
                            JSONObject jsonObject = new JSONObject();
                            if ("id".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getAdviseId());
                            } else if ("adminId".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getAdminId());
                            } else if ("creator".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getCreator());
                            } else if ("title".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getTitle());
                            } else if ("content".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getContent());
                            } else if ("createTime".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getCreateTime());
                            } else if ("status".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getStatus());
                            } else if ("replyContent".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getReplyContent());
                            } else if ("replyTime".equals(type)) {
                                jsonObject.put("value", ((Advice) single).getReplyTime());
                            }
                            jsonArray.add(jsonObject);
                        }
                        result.setDataEntry("total", resultAdvice.size());
                        result.setDataJsonArray("values", jsonArray);
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                } else if (value != null) {
                    // 精确查询
                    Advice advice = new Advice();
                    if ("id".equals(type)) {
                        advice.setAdviseId(value);
                    } else if ("adminId".equals(type)) {
                        advice.setAdminId(value);
                    } else if ("creator".equals(type)) {
                        advice.setCreator(value);
                    } else if ("title".equals(type)) {
                        advice.setTitle(value);
                    } else if ("content".equals(type)) {
                        advice.setContent(value);
                    } else if ("createTime".equals(type)) {
                        advice.setCreateTime(value);
                    } else if ("status".equals(type)) {
                        advice.setStatus(value);
                    } else if ("replyContent".equals(type)) {
                        advice.setReplyContent(value);
                    } else if ("replyTime".equals(type)) {
                        advice.setReplyTime(value);
                    }
                    List<Object> resultAdvice;  //查询返回的用户信息
                    try {
                        resultAdvice = adviceDao.adviceList(null, advice, null, null, null, null);
                        if (resultAdvice.size() != 0) {
                            result.setMsg("success");
                        } else {
                            result.setMsg("no record!");
                        }
                        result.setStatus(200);
                        int total = resultAdvice.size();
                        result.setDataEntry("total", total);
                        result.setDataObject("value", total == 0 ? new JSONObject() : resultAdvice.get(0));
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                } else {
                    // 错误
                    result.setStatus(400);
                    result.setMsg("invalid request");
                }
            } else {
                // 分页
                String start = req.getParameter("start");  //当前页
                String pageSize = req.getParameter("pagesize");  //页记录数
                if (start != null && pageSize != null) {
                    int s = 0;
                    int ps = 0;
                    List<Object> resultAdvice;  //查询返回的用户信息

                    if (!StringUtil.isEmpty(start)) {
                        s = Integer.parseInt(start);
                    }
                    if (!StringUtil.isEmpty(pageSize)) {
                        ps = Integer.parseInt(pageSize);
                    }
                    PageBean pageBean = new PageBean(s, ps);
                    try {
                        resultAdvice = adviceDao.adviceList(pageBean, new Advice(), null, null, null, null);
                        if (resultAdvice.size() != 0) {
                            result.setDataEntry("total", resultAdvice.size());
                            result.setStatus(200);
                            result.setMsg("success");
                            JSONArray jsonArray = new JSONArray();

                            for (Object single : resultAdvice) {
                                JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                                jsonArray.add(jsonObject);
                            }
                            result.setDataJsonArray("values", jsonArray);
                        } else {
                            result.setStatus(200);
                            result.setMsg("No record!");
                        }
                    } catch (Exception e) {
                        //查询失败
                        result.setStatus(401);
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        int total = adviceDao.adviceCount(new Advice(), null, null, null, null);
                        result.setStatus(200);
                        result.setMsg("success");
                        result.setDataEntry("total", total);
                    } catch (Exception e) {
                        result.setStatus(500);
                        result.setMsg("failed");
                    }
                }
            }
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 修改
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject jsonObjectA = RequestUtil.getJsonFromRequest(req);
        if (jsonObjectA != null) {
            String reply = jsonObjectA.getString("replyContent");
            String adminId = jsonObjectA.getString("adminId");
            Advice advice = new Advice();
            advice.setAdviseId(jsonObjectA.getString("id"));
            advice.setReplyContent(reply);
            advice.setAdminId(adminId);
            if (StringUtil.isNotEmpty(reply)) {
                advice.setStatus("2");
                String now1 = DateUtil.nowTime();
                String now2 = DateUtil.parseTime(now1);
                advice.setReplyTime(now2);
            } else {
                advice.setStatus("1");
            }

            JsonWrapper result = new JsonWrapper();

            try {
                int modifyNum = adviceDao.adviceModify(advice);
                if (modifyNum == 1) {
                    result.setStatus(200);  //修改成功
                    result.setMsg("success");
                    List<Object> adviceList = adviceDao.adviceList(null, new Advice(jsonObjectA.getString("id")), null, null, null, null);
                    JSONObject advise = JsonWrapper.parseFromObject(adviceList.get(0));

                    sendMessage(advise.getString("creator"), "您的反馈【" + advise.getString("title") + " —— " + advise.getString("content") + "】已被回复， 回复内容：" + reply + ", 谢谢您的反馈，祝您使用愉快!");
                    result.setDataEntry("total", 1);
                    result.setDataJsonObject("value", advise);
                } else {
                    result.setStatus(400);  //修改失败
                    result.setMsg("修改成功的记录：0条");
                }
            } catch (Exception e) {
                result.setStatus(401);  //修改失败
                result.setMsg("failed");
                e.printStackTrace();
            }
            ResponseUtil.write(resp, result);
        } else {
            ResponseUtil.writeBadRequest(resp);
        }
    }

    /**
     * 删除
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JsonWrapper result = new JsonWrapper();
        try {
            int delNum = adviceDao.adviceDelete(req.getParameter("id"));
            if (delNum == 1) {
                result.setStatus(200);  //删除成功
                result.setMsg("success");
                result.setDataEntry("total", 1);
            } else {
                result.setStatus(400);  //删除失败
                result.setMsg("删除成功的记录：0条");
            }
        } catch (Exception e) {
            result.setStatus(401);  //删除失败
            result.setMsg("failed");
            e.printStackTrace();
        }
        ResponseUtil.write(resp, result);
    }

    /**
     * 增加
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Advice advice = new Advice();
        advice.setCreator(req.getParameter("userId"));
        advice.setTitle(req.getParameter("title"));
        advice.setContent(req.getParameter("content"));
        String now1 = DateUtil.nowTime();
        String now2 = DateUtil.parseTime(now1);
        advice.setCreateTime(now2);
        advice.setStatus("0");

        JsonWrapper result = new JsonWrapper();

        try {
            boolean result1 = adviceDao.adviceAdd(advice);
            if (result1) {
                result.setStatus(200);  //
                result.setMsg("success");
                result.setDataEntry("total", 1);
            } else {
                result.setStatus(400);  //
                result.setMsg("添加成功的记录：0条");
            }
        } catch (Exception e) {
            result.setStatus(401);  //
            result.setMsg("failed");
            e.printStackTrace();
        }
        ResponseUtil.write(resp, result);
    }

    private void sendMessage(String rid, String content) throws Exception {
        Message message = new Message();
        message.setSendId("1");
        message.setReceiveId(rid);
        message.setContent(content);
        message.setStatus("0");
        message.setSendTime(DateUtil.nowSymbolTime());
        messageDao.messageAdd(message);
    }
}
